import * as moment from 'moment';
import { EssayEntity } from 'src/module/essay/entities/essay.entity';
import { UsersEntity } from 'src/module/user/entities/user.entity';
import {
  BeforeInsert,
  BeforeUpdate,
  Column,
  Entity,
  JoinColumn,
  JoinTable,
  ManyToMany,
  ManyToOne,
  PrimaryColumn,
} from 'typeorm';
import { v4 as uuidv4 } from 'uuid';

@Entity({ name: 'tag' })
export class TagEntity {

  constructor(partial?: Partial<TagEntity>) {
    Object.assign(this, partial);
  }

  @PrimaryColumn()
  id: string = uuidv4();

  @Column({ type: 'varchar', length: 30 })
  tagname: string;

  @Column({ type: 'int', name: 'sort_order' })
  sortOrder: number;

  @ManyToOne(() => UsersEntity, (user) => user.tags)
  @JoinColumn({ name: 'user_id' })
  user: UsersEntity;

  @ManyToMany(() => EssayEntity, (essay) => essay.tags)
  @JoinTable({ name: 'tag_essay' })
  essays: EssayEntity[];

  @Column({ type: 'varchar', nullable: true })
  created_at: string;

  @Column({ type: 'varchar', nullable: true })
  updated_at: string;

  @BeforeInsert()
  createDates() {
    this.created_at = moment().format('YYYY-MM-DD HH:mm:ss');
  }

  @BeforeUpdate()
  updateDates() {
    this.updated_at = moment().format('YYYY-MM-DD HH:mm:ss');
  }
}
